import styles from './list.module.scss'
import { Input,Button,Spin, Empty } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import type { questionType } from '@/utils/type'
import QuestionCard from '@/components/questionCard'
import { useDebounceFn, useRequest, useTitle} from 'ahooks'

import { useState,useRef, useEffect,useMemo } from 'react'


import useSearchQuestion from '@/hooks/useSearchQuestion'
import { useSearchParams } from 'react-router-dom'
import { getQuestionListApi } from '@/apis/question'





const List = ()=>{
  useTitle('Shaun-问卷列表')


  const {inputRef,handleSearch} =useSearchQuestion()
  const [started,setStarted] = useState(false)   //是否开始下拉刷新
  const [page,setPage] = useState(1)
  const [list,setList] = useState([])
  const [total,setTotal] = useState(0)
  const haveMoreData = list.length < total   //是否还有更多数据
  const [searchParams] = useSearchParams()
  const keyword = searchParams.get('keyword') || ''

  useEffect(()=>{
    setPage(1)
    setList([])
    setTotal(0)
    setStarted(false)
  },[keyword])


  //加载数据列表
  const {run:load,loading} = useRequest(async()=>{
    const data = await getQuestionListApi({
      page,
      pageSize:5,
      keyword
    })
    return data
  },{
    manual:true,
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    onSuccess:(res:any)=>{
      const {list:l=[],total=0} = res
      setList(list.concat(l))
      setTotal(total)
      setPage(page+1)
    }
  })


  //防抖
  const containerRef = useRef<HTMLDivElement>(null)
  const {run : tryLoadMore } = useDebounceFn(
    ()=>{
      const elem = containerRef.current
      if(elem ==null) return
      const domRect = elem.getBoundingClientRect()
      if(domRect == null) return
      const {bottom} = domRect
      if(bottom<=document.body.clientHeight) {
        console.log('load more....')
        setStarted(true)
        load()
      }
    },{wait:1000}
  )

   // 1. 当页面加载，或者 url 参数（keyword）变化时，触发加载
  useEffect(() => {
    tryLoadMore() // 加载第一页，初始化
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams])

  // 2. 当页面滚动时，要尝试触发加载
  useEffect(() => {
    if (haveMoreData) {
      window.addEventListener('scroll', tryLoadMore) // 防抖
    }

    return () => {
      window.removeEventListener('scroll', tryLoadMore) // 解绑事件，重要！！！
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams, haveMoreData])

  // LoadMore Elem
  const LoadMoreContentElem = useMemo(() => {
    if (!started || loading) return <Spin />
    if (total === 0) return <Empty description="暂无数据" />
    if (!haveMoreData) return <span>没有更多了...</span>
    return <span>开始加载下一页</span>
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [started, loading, haveMoreData])


 
  return (
    <div className={styles.container}>
      {/* 头部 */}
      <div className={styles.header}>
        {/* 左部 */}
        <div className={styles.left}>我的问卷</div>
        {/* 右部 */}
        <div className={styles.right}>
           <Input ref={inputRef}   placeholder='请输入标题'></Input>
           <Button icon={<SearchOutlined />} onClick={handleSearch} />
        </div>
      </div>
      {/* 主体列表 */}
      <div className={styles.list}>
          {loading ? ''  : list.map((item:questionType)=>(
             <QuestionCard  item={item} key={item.id}  />
          ))}
      </div>
      {/* 分页 */}
      <div className={styles.pagination} ref={containerRef}>{LoadMoreContentElem}</div>
    </div>
  )
}


export default List
